package com.fengkun.integration.common.trace;

import com.fengkun.integration.common.util.UUIDUtils;
import org.springframework.util.StringUtils;

public enum TraceUtil {

    INSTANCE;

    private ThreadLocal<String> traceIdHolder = new ThreadLocal();
    private ThreadLocal<TraceData> traceDataThreadLocal = new ThreadLocal();

    private TraceUtil() {
    }

    public void setTraceId(String traceId) {
        this.traceIdHolder.set(traceId);
    }

    public String getTraceId() {
        String traceId = (String)this.traceIdHolder.get();
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUIDUtils.getUuid();
            this.traceIdHolder.set(traceId);
        }

        return traceId;
    }

    public String getTraceId1() {


        return this.traceIdHolder.get();
    }

    public void setTraceData(TraceData traceData) {
        this.traceDataThreadLocal.set(traceData);
    }

    public TraceData getTraceData() {
        TraceData traceData = this.traceDataThreadLocal.get();
        if (null == traceData) {
            traceData = new TraceData();
            traceData.setTraceId(UUIDUtils.getUuid());

            this.traceDataThreadLocal.set(traceData);
        }

        return traceData;
    }

    public void clear() {
        this.traceIdHolder.remove();
        this.traceDataThreadLocal.remove();
    }
}
